package com.hmjk.health.background.data;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.text.format.Time;
import android.util.Log;

import com.hmjk.health.HealthApp;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.background.DatabaseHelper;
import com.hmjk.health.background.NetService;
import com.hmjk.health.util.ADrugReminder;
import com.hmjk.health.util.AReminder;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.ReminderList;

public class DrugReminderUpdated extends DataUpdated{
	private static String TAG = DrugReminderUpdated.class.getSimpleName();
	//public static final String TYPE_FAMILY = "family";
	//public static final String TYPE_USER = "user";
	//public static final String TYPE_ALL = "all";
	private ArrayList<String> mTIDArray = new ArrayList<String>();	
	private boolean working = false;
	private boolean doSingle = false;
	private int index = 0;
	
	private void logd(String info){
		Log.d(TAG, info);
	}
	
	public DrugReminderUpdated(HealthApp app, DataManager dm, DataUpdated base) {
		super(app, dm,base);
		UPDATE_TIME = 60 * 60 * 1000;
		mBaseData.setNotifer(DataManager.F_DRUG_REMINDER, this);
	}

	@Override
	public void setUserData(Object data) {
		// TODO Auto-generated method stub
		reqTime = 0;
		upTime = 0;
	}

	@Override
	public long delay() {
		long curMs = System.currentTimeMillis();
		long del = curMs - upTime;
		logd("delay curMs="+curMs+" upTime="+upTime+" del="+del);
		if(del >= UPDATE_TIME){
			logd("delay 0");
			return 0;
		}else{
			logd("delay (UPDATE_TIME - del) = "+(UPDATE_TIME - del));
			return (UPDATE_TIME - del);
		}
	}
	
	private void getTids(){
		JSONObject json = (JSONObject) mBaseData.check(null);
	
		mTIDArray.clear();
		index = 0;
		if(json != null){
			try {
				JSONArray ar = json.getJSONArray("array");
				int len = ar.length();
				for(int i = 0; i < len; i++){
					JSONObject e = ar.getJSONObject(i);
					String tid = e.getString("tid");
					String type = e.getString("type");
					String name = e.getString("name");
					logd("device, tid=" + tid + ", type=" + type);
					
					if(DEV_DATA.isHealthDev(type)){
						mTIDArray.add(tid);
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}
	
	private void doNextRequest(){
		if(doSingle){
			doSingle = false;
			working = false;
			return;
		}
		
		String uid = mApp.getUID();
		if(uid == null){
			Log.e(TAG, "doNextRequest uid == null stoped!");
			working = false;
		}
		int size = mTIDArray.size();
		
		if(index < size){
			while(index < size){
				String tid = mTIDArray.get(index);
				if(checkReminder(uid,tid)){
					index ++;
					break;
				}else{
					index ++;
				}
			}
			if(index >= size)
				working = false;
		}else{
			working = false;
		}
	}
	
	private void doRequest(String uid){
		getTids();
		int size = mTIDArray.size();
		logd("doRequest:size="+size);
		doSingle = false;
		if(size > 0){
			index = 0;
			String tid = mTIDArray.get(index);
			working = true;
			if(checkReminder(uid,tid)){
				index ++;
			}else{
				index ++;
				doNextRequest();
			}
		}else{
			Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
			i.putExtra("type",DataManager.F_DRUG_REMINDER);
			i.putExtra("state", false);
			i.putExtra("tid", "");
			mApp.sendBroadcast(i);
		}
	}
	
	private void doSingleRequest(String uid, String tid){
		working = true;
		doSingle = true;
		checkReminder(uid,tid);
	}
	
	
	private boolean checkReminder(String uid,String tid){		//index = -1 get all
		Intent si = new Intent(NetService.GET_DATA_ACTION);
		si.putExtra("sub_act", NetService.GET_DRUG_REMINDER);
		si.putExtra("uid", uid);
		si.putExtra("tid", tid);
		si.putExtra("terminaltype", 0);
		si.putExtra("dex", 255);
		
		Time t = new Time();
		t.setToNow();
		String stamp = "GET_DRUG_REMINDER" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
		
		return true;
	}

	@Override
	public boolean grab() {

		String uid = mApp.getUID();
		logd("grab uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grab working now");
			return false;
		}
		
		long curMs = System.currentTimeMillis();
		logd("grab curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > UPDATE_TIME){
			doRequest(uid);
			reqTime = curMs;
			logd("grab req sent!");
			return true;
		}
		return false;
	}

	@Override
	public boolean grabByUser() {
		String uid = mApp.getUID();
		logd("grabByUser uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grabByUser downloading");
			return false;
		}
		
		long curMs = System.currentTimeMillis();
		logd("grabByUser curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > 30 * 1000){
			doRequest(uid);
			reqTime = curMs;
			logd("grabByUser req sent!");
			return true;
		}
		return false;
	}
	
	@Override
	public boolean grabByUserWithSingleArgs(Object args){
		if(args == null)
			return false;
		
		String argString = (String)args;
		if(argString.trim().isEmpty())
			return false;
		
		String uid = mApp.getUID();
		logd("grabByUserWithSingleArgs uid="+uid);
		if(uid == null)
			return false;
		
		if(working){
			logd("grabByUserWithSingleArgs downloading");
			return false;
		}
				
		long curMs = System.currentTimeMillis();
		logd("grabByUserWithSingleArgs curMs="+curMs+" reqTime="+reqTime);
		if((curMs - reqTime) > 10 * 1000){
			doSingleRequest(uid, argString);
			reqTime = curMs;
			logd("grabByUserWithSingleArgs req sent!");
			return true;
		}
		return false;
	}	
	

	@Override
	public void receive(String stamp, String sjson) {
		DatabaseHelper dh = mDm.getDatabaseHelper();
		String table_name;
		
		if(stamp.startsWith("GET_DRUG_REMINDER")){
			if(sjson != null){
				boolean update = false;
				try {
					JSONObject json = new JSONObject(sjson);
					int code = json.getInt("code");
					if(code == 200){
						String state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							JSONObject recdata = json.getJSONObject("recdata");
							JSONObject senddata = json.getJSONObject("senddata");
							String tid = senddata.getString("tid");
						    
							if(recdata != null){
								upTime = System.currentTimeMillis();
								if(recdata.has("remindarr")){
									JSONArray arr = recdata.getJSONArray("remindarr");
									int size = arr.length();
									for(int i = 0; i < size; i++){
										JSONObject o = arr.getJSONObject(i);

										table_name = dh.checkDrugReminderTable(tid);
										if(table_name == null)
										{
											table_name = dh.createDrugReminderTable(tid);
										}
										
										ContentValues cv = new ContentValues();

										String sub_account = o.getString("subcode");
										cv.put(DatabaseHelper.REMIND_SUB_CODE, sub_account);
										
										String s = o.getString("isopen");
										cv.put(DatabaseHelper.REMIND_STATE, s);

										String index =  o.getString("dex");
										cv.put(DatabaseHelper.REMIND_INDEX, index);
										
										String mode = o.getString("remindmode");
										cv.put(DatabaseHelper.REMIND_MODE, mode);
										
										String timeStr = o.getString("remind");
										cv.put(DatabaseHelper.REMIND_TIME, timeStr);
										
										String tip = o.getString("remindmsg");
										cv.put(DatabaseHelper.REMIND_MSG, tip);
										
										String ter_type = o.getString("terminaltype");
										cv.put(DatabaseHelper.REMIND_TERMINAL_TYPE, ter_type);
										
										JSONArray drugInfo = o.getJSONArray("drugarr");
										cv.put(DatabaseHelper.REMIND_DRUG_INFO, drugInfo.toString());
										
										long up_time = o.getLong("updatetime");
										cv.put(DatabaseHelper.REMIND_UPTIME, up_time);
										
										dh.updateReminderTable(table_name, sub_account, cv);
										}

									}
								update = true;
								}
								
							}
						}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Intent i = new Intent(DataManager.DATA_UPDATE_ACTION);
				i.putExtra("type",DataManager.F_DRUG_REMINDER);
				i.putExtra("state", update);
				mApp.sendBroadcast(i);
			}
		}else if(stamp.startsWith("COMMIT_DRUG_REMINDER")){
			if(sjson != null){
				String state = "af";
				int code = 400;
				try {
					JSONObject json = new JSONObject(sjson);
					code = json.getInt("code");
					if(code == 200){
						state = json.getString("state");
						if(state.equalsIgnoreCase("00")){
							JSONObject sd = json.getJSONObject("senddata");

							String tid = sd.getString("tid");
                            
							table_name = dh.checkDrugReminderTable(tid);
							if(table_name == null)
							{
								table_name = dh.createDrugReminderTable(tid);
							}
							
							ContentValues cv = new ContentValues();

							String sub_account = sd.getString("subcode");
							cv.put(DatabaseHelper.REMIND_SUB_CODE, sub_account);							                      
							
							String mode = sd.getString("remindmode");
							cv.put(DatabaseHelper.REMIND_MODE, mode);
							
							cv.put(DatabaseHelper.REMIND_TIME, sd.getString("remind"));
							
							String tip = sd.getString("remindmsg");
							cv.put(DatabaseHelper.REMIND_MSG, tip);	
							
							String ter_type = sd.getString("terminaltype");
							cv.put(DatabaseHelper.REMIND_TERMINAL_TYPE, ter_type);
							
							JSONArray drugArry = sd.getJSONArray("drugarr");
							cv.put(DatabaseHelper.REMIND_DRUG_INFO, drugArry.toString());	
							
							long up_time = sd.getLong("updatetime");
							cv.put(DatabaseHelper.REMIND_UPTIME, up_time);
							
							int opt = Integer.parseInt(sd.getString("opt"));
                            String dex; 
                            if(opt == AReminder.NEW_OPEN_OP || opt == AReminder.NEW_OFF_OP)
                            {
                            	JSONObject recdata = json.getJSONObject("recdata");
                            	dex = recdata.getString("dex");
                            }
                            else
                            {
                            	dex = sd.getString("dex");
                            }
	
							cv.put(DatabaseHelper.REMIND_INDEX, dex);							
							
                            String s;
							switch(opt)
							{
							case AReminder.NEW_OPEN_OP:
								s = "1";
								cv.put(DatabaseHelper.REMIND_STATE, s);								
								dh.addOne2Table(table_name, cv);								
								break;
							case AReminder.NEW_OFF_OP:
								s = "0";
								cv.put(DatabaseHelper.REMIND_STATE, s);								
								dh.addOne2Table(table_name, cv);									
								break;
							case AReminder.MODIFY_OPEN_OP:
								s ="1";
								cv.put(DatabaseHelper.REMIND_STATE, s);		
								dh.updateReminderTable(table_name,sub_account,cv);
								break;								
							case AReminder.MODIFY_OFF_OP:
								s = "0";
								cv.put(DatabaseHelper.REMIND_STATE, s);								
								dh.updateReminderTable(table_name,sub_account,cv);
								break;
							case AReminder.DELETE_OP:
								dh.delateOneItemInReminderTable(table_name,sub_account);
								break;
								
							}

					}
				}
				}catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					state = "af";
				}
				Intent i = new Intent(DataManager.DATA_COMMIT_RESULT);
				i.putExtra("type",DataManager.F_DRUG_REMINDER);
				i.putExtra("state", state);
				i.putExtra("code", code);
				mApp.sendBroadcast(i);
			}
		}
		
	}
	
	@Override
	/*only check 1 param*/
	public Object check(String[] arg) {
		if((arg != null) && (arg.length > 0)){
			DatabaseHelper dh = mDm.getDatabaseHelper();			
			String tid = arg[0];
			String table = null;
			ReminderList list = new ReminderList();
			table = dh.checkDrugReminderTable(tid);
			
			Cursor c = dh.getItemsInTable(table);
			if(c.getCount() > 0){
				while(c.moveToNext()){
					int terminal_type = Integer.parseInt(c.getString(c.getColumnIndex(DatabaseHelper.REMIND_TERMINAL_TYPE)));										
					ADrugReminder rem = new ADrugReminder(tid,terminal_type);
					rem.Index = Integer.parseInt(c.getString(c.getColumnIndex(DatabaseHelper.REMIND_INDEX)),16);
					rem.isopen = Integer.parseInt(c.getString(c.getColumnIndex(DatabaseHelper.REMIND_STATE)));
					rem.remind_mode = Integer.parseInt(c.getString(c.getColumnIndex(DatabaseHelper.REMIND_MODE)));
					String timeStr = c.getString(c.getColumnIndex(DatabaseHelper.REMIND_TIME));
					rem.time.setByHexStr(timeStr);
					rem.subcode = c.getString(c.getColumnIndex(DatabaseHelper.REMIND_SUB_CODE));
					rem.tipContent = c.getString(c.getColumnIndex(DatabaseHelper.REMIND_MSG));
					rem.update_time = c.getLong(c.getColumnIndex(DatabaseHelper.REMIND_UPTIME));
					String druginfo = c.getString(c.getColumnIndex(DatabaseHelper.REMIND_DRUG_INFO));
					rem.setDoseList(druginfo);
				    
					list.addAReminder(rem);
				}
			}
			c.close();
			return list;
		}
		return null;
	}

	@Override
	public boolean commit(Object data) {
		ADrugReminder rem = (ADrugReminder)data;
		
		Intent si = new Intent(NetService.COMMIT_DATA_ACTION);
		si.putExtra("sub_act", NetService.COMMIT_DRUG_REMINDER);
		
		
		si.putExtra("uid", mApp.getUID());
        si.putExtra("tid", rem.tid);
        si.putExtra("terminaltype", Integer.toString(rem.devType));
        si.putExtra("remindmode",Integer.toString(rem.remind_mode));
        si.putExtra("opt", AReminder.int2HexStr(rem.opt));
        si.putExtra("dex", AReminder.int2HexStr(rem.Index));
        si.putExtra("subcode", rem.subcode);
        si.putExtra("remind", rem.time.getHexStr());
        si.putExtra("remindmsg", rem.tipContent);
        si.putExtra("updatetime", System.currentTimeMillis());
        si.putExtra("drugarr", rem.getDoseListJSONArrayStr());
		
		Time t = new Time();
		t.setToNow();
		String stamp = "COMMIT_DRUG_REMINDER" + t.toString(); 
		si.putExtra("stamp",stamp);
		mApp.addNetHandler(stamp,mDm.getBackGroundHandler());
		mApp.startService(si);
		return true;
	}

	@Override
	public void release() {
		// TODO Auto-generated method stub
		
	}
}
